from django.contrib.auth import authenticate
from rest_framework.views import APIView
from rest_framework_simplejwt.tokens import RefreshToken, AccessToken

from utils.ResponseResult import success_result_json, fail_result_json
from utils.TokenUtils import generate_access_token, generate_refresh_token
from .models import user as UserModel
import json


class UserLoginView(APIView):
    def post(self, request):
        """
        self 继承父类
        :param request:
        :return:
        """
        print(f"self: {self.allowed_methods}")
        username = request.data.get("userName")
        password = request.data.get("password")
        # 登录方式：0:工号密码 1:邮箱 2:短信
        login_mode = request.data.get("loginMode")
        print(f"测试登录参数：{username}, {password}, {login_mode}")
        if not username or not password:
            return fail_result_json(msg="用户和密码不能为空", code=403)
        if login_mode not in [0, 1, 2]:
            login_mode = 0
        if login_mode == 0:
            # authenticate 是基于django5自带auth认证系统实现（自带的user数据库表）
            # user = authenticate(username=user_name, password=password)
            try:
                user = UserModel.objects.get(user_no=username)
                if not user:
                    return fail_result_json(msg="无效工号，用户不存在")
                if password != user.password:
                    return fail_result_json(msg="密码错误", code=403)
                # 用户信息正常
                # access_token = AccessToken.for_user(user)
                # refresh_token = RefreshToken.for_user(user)
                access_token = generate_access_token(user)
                refresh_token = generate_refresh_token(user)
                response = {
                    'access_token': str(access_token),
                    'refresh_token': str(refresh_token)
                }
                return success_result_json(data=response, msg="登录成功")
            except UserModel.DoesNotExist:
                return fail_result_json(msg="用户不存在，确认工号是否存在", code=403)
            except Exception as e:
                return fail_result_json(msg=f"登录异常，{e},请联系管理员", code=403)
        if login_mode == 1:
            return user_email_login(username, password)
        if login_mode == 2:
            return user_phone_login(username, password)


def user_login(request):
    post_body = request.body
    json_param = json.loads(post_body.decode("utf-8"))
    if json_param:
        username = json_param.get("userName")
        password = json_param.get("password")
        # 登录方式：0:工号密码 1:邮箱 2:短信
        login_mode = json_param.get("loginMode")
        if not username or not password:
            return fail_result_json(msg="用户和密码不能为空", code=403)
        if login_mode not in [0, 1, 2]:
            login_mode = 0
        if login_mode == 0:
            return user_password_login(username, password)
        if login_mode == 1:
            return user_email_login(username, password)
        if login_mode == 2:
            return user_phone_login(username, password)
    else:
        return fail_result_json(msg="用户和密码不能为空", code=403)


def user_password_login(username, pwd):
    try:
        user = UserModel.objects.get(user_no=username)
        if not user:
            return fail_result_json(msg="无效工号，用户不存在")
        if pwd != user.password:
            return fail_result_json(msg="密码错误", code=403)
        return success_result_json(msg="登录成功")
    except UserModel.DoesNotExist:
        return fail_result_json(msg="用户不存在，确认工号是否存在", code=403)
    except Exception as e:
        return fail_result_json(msg=f"登录异常，{e},请联系管理员", code=403)


def user_email_login(email, code):
    pass


def user_phone_login(phone, code):
    pass
